package com.dk.springmvc.ajax.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Controller
public class FileController {

    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile uploadFile, HttpSession session) throws IOException {
        String realPath = session.getServletContext().getRealPath(File.separator + "static" + File.separator + "upload");
        String filename = uploadFile.getOriginalFilename();
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 一般要做随机文件名处理
        uploadFile.transferTo(new File(realPath + File.separator + filename));
        return "success";
    }


    @GetMapping("/download")
    public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
        // 获取ServletContext
        ServletContext servletContext = session.getServletContext();
        // 获取应用程序根目录并拼接下载文件路径
        String realPath = servletContext.getRealPath("/static/downloadFile/spring复习.md");
        // 创建输入流
        InputStream inputStream = new FileInputStream(realPath);
        // 创建字节数组，长度为文件字节数
        byte[] bytes = new byte[inputStream.available()];
        // 读取文件，并将字节码赋给byte数组
        inputStream.read(bytes);
        // 创建HttpHeaders对象设置头信息
        MultiValueMap<String, String> header = new HttpHeaders();

        // 设置下载方式和下载的文件名
        header.add(HttpHeaders.ACCEPT_CHARSET, "UTF-8");
        header.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");
        // 处理下载的文件名中文乱码的问题
        String filename = URLEncoder.encode("测试.md", StandardCharsets.UTF_8);
        header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + filename);
        // 设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        // 创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, header, statusCode);
        // 关闭输入流
        inputStream.close();

        return responseEntity;
    }
}
